<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发票管理系统 - 发票上传</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }

        .sidebar {
            height: 100vh;
            background-color: #343a40;
            color: white;
            position: fixed;
            width: 250px;
            padding-top: 20px;
        }

            .sidebar .nav-link {
                color: rgba(255, 255, 255, 0.8);
                margin-bottom: 5px;
                border-radius: 5px;
                padding: 10px 15px;
            }

                .sidebar .nav-link:hover {
                    background-color: #495057;
                    color: white;
                }

                .sidebar .nav-link.active {
                    background-color: #007bff;
                    color: white;
                }

        .main-content {
            margin-left: 250px;
            padding: 20px;
        }

        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }

            .upload-area:hover {
                border-color: #0d6efd;
                background-color: #f8f9ff;
            }

            .upload-area i {
                font-size: 48px;
                color: #0d6efd;
                margin-bottom: 15px;
            }

        .progress {
            height: 25px;
            margin-bottom: 20px;
        }

        .invoice-preview {
            max-width: 100%;
            max-height: 300px;
            margin-top: 20px;
            display: none;
        }

        .invoice-info-card {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center mb-4">
            <h4>发票管理系统</h4>
        </div>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="welcome.html">
                    <i class="bi bi-house-door me-2"></i>首页
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="upload.html">
                    <i class="bi bi-upload me-2"></i>发票上传
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="query.html">
                    <i class="bi bi-search me-2"></i>发票查询
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="statistic.html">
                    <i class="bi bi-bar-chart me-2"></i>发票统计
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" id="logoutBtn">
                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                </a>
            </li>
        </ul>
    </div>

    <div class="main-content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col">
                    <h2>发票上传</h2>
                    <p class="text-muted">上传图片格式的发票文件，系统将自动识别发票信息</p>
                </div>
            </div>

            <div class="row">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">上传发票</h5>
                            <div id="uploadArea" class="upload-area">
                                <i class="bi bi-cloud-arrow-up"></i>
                                <h5>点击或拖拽文件到此处上传</h5>
                                <p class="text-muted">支持 JPG、PNG 格式，文件大小不超过 16MB</p>
                                <input type="file" id="fileInput" accept="image/jpeg,image/png" style="display: none;">
                            </div>

                            <div class="progress" style="display: none;">
                                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                            </div>

                            <div id="uploadStatus" class="alert" style="display: none;"></div>

                            <img id="invoicePreview" class="invoice-preview img-thumbnail" alt="发票预览">
                        </div>
                    </div>

                    <div class="card invoice-info-card" id="invoiceInfoCard" style="display: none;">
                        <div class="card-body">
                            <h5 class="card-title">发票信息</h5>
                            <form id="invoiceForm">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="invoiceNumber" class="form-label">发票号码</label>
                                            <input type="text" class="form-control" id="invoiceNumber" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="invoiceDate" class="form-label">开票日期</label>
                                            <input type="date" class="form-control" id="invoiceDate" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="amount" class="form-label">金额</label>
                                            <input type="number" step="0.01" class="form-control" id="amount" required>
                                        </div>
                                        <div class="mb-3">
                                            <label for="taxAmount" class="form-label">税额</label>
                                            <input type="number" step="0.01" class="form-control" id="taxAmount">
                                        </div>
                                        <div class="mb-3">
                                            <label for="totalAmount" class="form-label">合计金额</label>
                                            <input type="number" step="0.01" class="form-control" id="totalAmount" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="sellerName" class="form-label">销售方名称</label>
                                            <input type="text" class="form-control" id="sellerName">
                                        </div>
                                        <div class="mb-3">
                                            <label for="sellerTaxId" class="form-label">销售方税号</label>
                                            <input type="text" class="form-control" id="sellerTaxId">
                                        </div>
                                        <div class="mb-3">
                                            <label for="buyerName" class="form-label">购买方名称</label>
                                            <input type="text" class="form-control" id="buyerName">
                                        </div>
                                        <div class="mb-3">
                                            <label for="buyerTaxId" class="form-label">购买方税号</label>
                                            <input type="text" class="form-control" id="buyerTaxId">
                                        </div>
                                        <div class="mb-3">
                                            <label for="invoiceType" class="form-label">发票类型</label>
                                            <select class="form-select" id="invoiceType">
                                                <option value="增值税专用发票">增值税专用发票</option>
                                                <option value="增值税普通发票">增值税普通发票</option>
                                                <option value="电子普通发票">电子普通发票</option>
                                                <option value="其他">其他</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="button" class="btn btn-secondary me-md-2" id="reRecognizeBtn">重新识别</button>
                                    <button type="submit" class="btn btn-primary">保存发票</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">操作指南</h5>
                            <ul class="list-group list-group-flush">
                                <li class="list-group-item">
                                    <i class="bi bi-check-circle text-success me-2"></i>确保发票图片清晰可读
                                </li>
                                <li class="list-group-item">
                                    <i class="bi bi-check-circle text-success me-2"></i>尽量上传正面拍摄的发票
                                </li>
                                <li class="list-group-item">
                                    <i class="bi bi-check-circle text-success me-2"></i>避免反光、阴影和遮挡
                                </li>
                                <li class="list-group-item">
                                    <i class="bi bi-check-circle text-success me-2"></i>系统将自动识别发票关键信息
                                </li>
                                <li class="list-group-item">
                                    <i class="bi bi-check-circle text-success me-2"></i>识别后请核对信息准确性
                                </li>
                            </ul>
                        </div>
                    </div>

                    <div class="card mt-4">
                        <div class="card-body">
                            <h5 class="card-title">最近上传</h5>
                            <div id="recentUploads" class="list-group">
                                <div class="list-group-item text-center text-muted">
                                    暂无最近上传记录
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 检查用户是否已登录
        const user_id = localStorage.getItem('user_id');
        if (!user_id) {
            window.location.href = 'index.html';
        }

        document.getElementById('logoutBtn').addEventListener('click', function () {
            localStorage.removeItem('user_id');
            window.location.href = 'index.html';
        });

        // 上传区域点击事件
        document.getElementById('uploadArea').addEventListener('click', function () {
            document.getElementById('fileInput').click();
        });

        // 拖拽上传功能
        const uploadArea = document.getElementById('uploadArea');

        uploadArea.addEventListener('dragover', function (e) {
            e.preventDefault();
            this.style.borderColor = '#0d6efd';
            this.style.backgroundColor = '#f8f9ff';
        });

        uploadArea.addEventListener('dragleave', function (e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';
            this.style.backgroundColor = '';
        });

        uploadArea.addEventListener('drop', function (e) {
            e.preventDefault();
            this.style.borderColor = '#ccc';
            this.style.backgroundColor = '';

            if (e.dataTransfer.files.length) {
                handleFileUpload(e.dataTransfer.files[0]);
            }
        });

        // 文件选择事件
        document.getElementById('fileInput').addEventListener('change', function () {
            if (this.files.length) {
                handleFileUpload(this.files[0]);
            }
        });

        // 重新识别按钮
        document.getElementById('reRecognizeBtn').addEventListener('click', function () {
            const imagePath = document.getElementById('invoicePreview').getAttribute('data-path');
            if (imagePath) {
                recognizeInvoice(imagePath);
            }
        });

        // 表单提交
        document.getElementById('invoiceForm').addEventListener('submit', function (e) {
            e.preventDefault();
            saveInvoice();
        });

        // 处理文件上传
        function handleFileUpload(file) {
            if (!file.type.match('image.*')) {
                showUploadStatus('请上传图片文件 (JPG/PNG)', 'danger');
                return;
            }

            if (file.size > 16 * 1024 * 1024) {
                showUploadStatus('文件大小不能超过16MB', 'danger');
                return;
            }

            // 显示上传进度
            const progressDiv = document.querySelector('.progress');
            const progressBar = document.getElementById('progressBar');
            progressDiv.style.display = 'block';
            progressBar.style.width = '0%';

            // 预览图片
            const reader = new FileReader();
            reader.onload = function (e) {
                const preview = document.getElementById('invoicePreview');
                preview.src = e.target.result;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);

            // 立即上传文件（不再模拟进度）
            const formData = new FormData();
            formData.append('file', file);
            formData.append('user_id', user_id);

            showUploadStatus('正在上传并识别发票...', 'info');

            fetch('http://127.0.0.1:8080/api/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    progressBar.style.width = '100%';
                    if (!response.ok) {
                        return response.json().then(err => { throw err; });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        showUploadStatus(data.error, 'danger');
                    } else {
                        showUploadStatus('发票识别成功', 'success');
                        document.getElementById('invoicePreview').setAttribute('data-path', data.image_path);
                        fillInvoiceForm(data.invoice_info);
                        document.getElementById('invoiceInfoCard').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showUploadStatus(error.error || '处理失败，请稍后再试', 'danger');
                })
                .finally(() => {
                    // 隐藏进度条
                    setTimeout(() => {
                        progressDiv.style.display = 'none';
                    }, 1000);
                });
        }

        // 修改 uploadFile 函数
        function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('user_id', user_id);

            fetch('http://127.0.0.1:8080/api/upload', {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => { throw err; });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        showUploadStatus(data.error, 'danger');
                    } else {
                        showUploadStatus('发票识别成功，请核对信息', 'success');
                        document.getElementById('invoicePreview').setAttribute('data-path', data.image_path);
                        fillInvoiceForm(data.invoice_info); // 直接使用返回的识别结果
                        document.getElementById('invoiceInfoCard').style.display = 'block';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showUploadStatus(error.error || '上传识别失败，请稍后再试', 'danger');
                });
        }


        // 填充发票表单
        function fillInvoiceForm(invoiceInfo) {
            document.getElementById('invoiceNumber').value = invoiceInfo.invoice_number || '';
            document.getElementById('invoiceDate').value = invoiceInfo.invoice_date || '';
            document.getElementById('amount').value = invoiceInfo.amount || '';
            document.getElementById('taxAmount').value = invoiceInfo.tax_amount || '';
            document.getElementById('totalAmount').value = invoiceInfo.total_amount || '';
            document.getElementById('sellerName').value = invoiceInfo.seller_name || '';
            document.getElementById('sellerTaxId').value = invoiceInfo.seller_tax_id || '';
            document.getElementById('buyerName').value = invoiceInfo.buyer_name || '';
            document.getElementById('buyerTaxId').value = invoiceInfo.buyer_tax_id || '';
            document.getElementById('invoiceType').value = invoiceInfo.invoice_type || '增值税普通发票';
        }

        // 保存发票
        function saveInvoice() {
            const imagePath = document.getElementById('invoicePreview').getAttribute('data-path');
            if (!imagePath) {
                showUploadStatus('请先上传发票图片', 'danger');
                return;
            }

            const invoiceInfo = {
                invoice_number: document.getElementById('invoiceNumber').value,
                invoice_date: document.getElementById('invoiceDate').value,
                amount: document.getElementById('amount').value,
                tax_amount: document.getElementById('taxAmount').value,
                total_amount: document.getElementById('totalAmount').value,
                seller_name: document.getElementById('sellerName').value,
                seller_tax_id: document.getElementById('sellerTaxId').value,
                buyer_name: document.getElementById('buyerName').value,
                buyer_tax_id: document.getElementById('buyerTaxId').value,
                invoice_type: document.getElementById('invoiceType').value
            };

            fetch('http://127.0.0.1:8080/api/save_invoice', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: user_id,
                    invoice_info: invoiceInfo,
                    image_path: imagePath
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        showUploadStatus(data.error, 'danger');
                    } else {
                        showUploadStatus('发票保存成功', 'success');
                        loadRecentUploads();
                        // 重置表单
                        setTimeout(() => {
                            document.getElementById('invoiceForm').reset();
                            document.getElementById('invoicePreview').style.display = 'none';
                            document.getElementById('invoiceInfoCard').style.display = 'none';
                            document.querySelector('.progress').style.display = 'none';
                            document.getElementById('uploadStatus').style.display = 'none';
                        }, 2000);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showUploadStatus('保存失败，请稍后再试', 'danger');
                });
        }

        // 显示上传状态
        function showUploadStatus(message, type) {
            const statusDiv = document.getElementById('uploadStatus');
            statusDiv.textContent = message;
            statusDiv.className = `alert alert-${type}`;
            statusDiv.style.display = 'block';
        }

        // 加载最近上传记录
        function loadRecentUploads() {
            fetch(`http://127.0.0.1:8080/api/query?user_id=${user_id}&limit=5`)
                .then(response => response.json())
                .then(data => {
                    const recentUploadsDiv = document.getElementById('recentUploads');

                    if (data.invoices && data.invoices.length > 0) {
                        recentUploadsDiv.innerHTML = '';

                        data.invoices.forEach(invoice => {
                            const item = document.createElement('a');
                            item.href = '#';
                            item.className = 'list-group-item list-group-item-action';
                            item.innerHTML = `
                                <div class="d-flex w-100 justify-content-between">
                                    <h6 class="mb-1">${invoice.invoice_number || '未识别号码'}</h6>
                                    <small>${invoice.invoice_date || ''}</small>
                                </div>
                                <p class="mb-1">${invoice.seller_name || '未知销售方'}</p>
                                <small class="text-muted">金额: ${invoice.total_amount || '0'} 元</small>
                            `;
                            item.addEventListener('click', function (e) {
                                e.preventDefault();
                                viewInvoiceImage(invoice.image_path);
                            });
                            recentUploadsDiv.appendChild(item);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading recent uploads:', error);
                });
        }

        // 查看发票图片
        function viewInvoiceImage(imagePath) {
            const preview = document.getElementById('invoicePreview');
            preview.src = `http://127.0.0.1:8080/uploads/${imagePath}`;
            preview.style.display = 'block';
        }

        // 页面加载时获取最近上传记录
        loadRecentUploads();
    </script>
</body>
</html>